# speech_recognizer.py
import base64
import requests
import json
from urllib import parse
import os
from config.config import Config

class BaiduASR:
    """百度语音识别处理类"""

    def __init__(self, config):
        self.config = config
        self.token_url = "https://aip.baidubce.com/oauth/2.0/token"
        self.asr_url = "https://vop.baidubce.com/server_api"

    def recognize(self, audio_file):
        """执行语音识别"""
        payload = self._build_payload(audio_file)
        headers = {'Content-Type': 'application/json'}

        try:
            response = requests.post(self.asr_url, headers=headers, data=payload)
            return self._parse_response(response)
        except Exception as e:
            print("API请求失败:", str(e))
            return None

    def _get_token(self):
        """获取API访问令牌"""
        params = {
            "grant_type": "client_credentials",
            "client_id": self.config.BAIDU_API_KEY,
            "client_secret": self.config.BAIDU_SECRET_KEY
        }
        return requests.get(self.token_url, params=params).json().get("access_token")

    def _build_payload(self, audio_file):
        """构建请求负载"""
        return json.dumps({
            "format": "wav",
            "rate": self.config.SAMPLE_RATE,
            "channel": self.config.CHANNELS,
            "cuid": "raspberry-pi-001",
            "speech": self._read_audio_file(audio_file),
            "len": os.path.getsize(audio_file),
            "token": self._get_token()
        }, ensure_ascii=False).encode('utf-8')

    @staticmethod
    def _read_audio_file(path):
        """读取并编码音频文件"""
        with open(path, "rb") as f:
            return base64.b64encode(f.read()).decode("utf8")

    @staticmethod
    def _parse_response(response):
        """解析API响应"""
        result = response.json()
        if 'result' in result:
            return result['result'][0]
        print("识别错误:", result.get('err_msg', '未知错误'))
        return None